package com.amit.hibernate;

import java.io.Serializable;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;

public class SIDgenerator  implements IdentifierGenerator{

	@Override
	public Serializable generate(SessionImplementor si, Object obj)
			throws HibernateException {
		String sid="JLC-001";
		
		try{
			Configuration cfg=new Configuration().configure();
			SessionFactory sf=cfg.buildSessionFactory();
			Session s=sf.openSession();
			Transaction tx=s.beginTransaction();
			
	Query q=s.createQuery("from Student stu ");

	int size=q.list().size();
	System.out.println(size);
	if(size!=0)
	{
		Query q1=s.createQuery("select max(sid) from Student stu ");
			System.out.println(q1);
		List list=q.list();
			
			int n=list.size();
			System.out.println(n);
		
				Object o=list.get(n-1);
				
				Student s1=(Student)o;
				System.out.println(s1.getSid());
				String id="";
				
			 id=s1.getSid();
			 
			String p2=id.substring(4);
			
			int x=Integer.parseInt(p2);
			System.out.println(x);
			x=x+1;
			if(x<=9){
				
				sid="JLC-00"+x;
				
			}
			else if(x<=99){
			
					sid="JLC-0"+x;
				}
			else if(x<=999){
			
					sid="JLC-"+x;
				}
				}
	
		}catch(Exception e){
			e.printStackTrace();
		}
		return sid;
	}

}
